import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../providers/comic_category_provider.dart';
import '../widget/header_item_title.dart';
import '../widget/manhua_list_item.dart';
import 'model/comic_category_item_model.dart';

class HomeContentWidget extends ConsumerWidget {
  final String categoryId;
  final bool isFirst;

  const HomeContentWidget(
      {super.key, this.isFirst = false, required this.categoryId});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final categoryDataAsync = ref.watch(comicCategoryProvider(categoryId));

    return Container(
      color: const Color(0xFF211839),
      child: SingleChildScrollView(
        child: Column(
          children: [
            isFirst
                ? Container()
                : Container(
                    height: MediaQuery.of(context).padding.top + 50,
                    color: const Color(0xFF211839),
                  ),

            // 使用 categoryDataAsync 来构建内容
            categoryDataAsync.when(
              loading: () => _buildLoadingState(),
              error: (error, stack) => _buildErrorState(error.toString()),
              data: (categories) => _buildContent(context, categories),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoadingState() {
    return Container(
      height: 200,
      child: const Center(
        child: CircularProgressIndicator(
          color: Colors.white,
        ),
      ),
    );
  }

  Widget _buildErrorState(String error) {
    return Container(
      height: 200,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              color: Colors.white54,
              size: 48,
            ),
            const SizedBox(height: 16),
            const Text(
              'Failed to load data',
              style: TextStyle(
                color: Colors.white54,
                fontSize: 16,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              error,
              style: const TextStyle(
                color: Colors.white38,
                fontSize: 12,
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent(
      BuildContext context, List<ComicCategoryData> categories) {
    if (categories.isEmpty) {
      return _buildEmptyState();
    }

    return Column(
      children: [
        // 如果有数据，显示第一个分类的内容
        if (categories.isNotEmpty)
          ..._buildStaticContentByType(context, categories),
      ],
    );
  }

  List<Widget> _buildStaticContentByType(
    BuildContext context,
    List<ComicCategoryData> categories,
  ) {
    final widgets = <Widget>[];
    for (var i = 0; i < categories.length; i++) {
      final category = categories[i];
      final type = category.moreType ?? 0;
      final categoryId = i.toString(); // 或 category.id

      widgets.addAll(
          _buildSectionForMoreType(context, type, category, categoryId));
    }
    return widgets;
  }

  List<Widget> _buildSectionForMoreType(
    BuildContext context,
    int type,
    ComicCategoryData category,
    String categoryId,
  ) {
    // 约定：1 = 横向推荐，2 = 网格，3 = 列表，0/其它 = 默认
    switch (type) {
      case 0:
        return [
          HeaderItemTitle(
            title: category.title ?? '',
            onTap: () => context.push(
                '/manhua_list/$categoryId/$type/${Uri.encodeComponent(category.title ?? '')}'),
          ),
          _hengxiangListWidgt(context, category, false),
          const SizedBox(height: 16),
        ];
      case 1:
        return [
          HeaderItemTitle(
            title: category.title ?? '',
            onTap: () => context.push(
                '/manhua_list/$categoryId/$type/${Uri.encodeComponent(category.title ?? '')}'),
          ),
          TwoByThreeGridDemo(similarComic: category.comics ?? const []),
          const SizedBox(height: 20),
        ];
      case 2:
        return [
          HeaderItemTitle(
            title: category.title ?? 'Most Viewed',
            onTap: () => context.push(
                '/manhua_list/$categoryId/$type/${Uri.encodeComponent(category.title ?? '')}'),
          ),
          const SizedBox(height: 16),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if (category.comics?.isNotEmpty == true) ...[
                  ManhListItem(comic: category.comics![0]),
                ],
                const SizedBox(height: 16),
                _hengxiangListWidgt(context, category, true),
              ],
            ), // 如果需要数据
          ),
          const SizedBox(height: 16),
        ];
      default:
        return [
          HeaderItemTitle(
            title: category.title ?? 'Other',
            onTap: () => context.push(
                '/manhua_list/$categoryId/$type/${Uri.encodeComponent(category.title ?? '')}'),
          ),
          _hengxiangListWidgt(context, category, false),
          const SizedBox(height: 16),
        ];
    }
  }

  Widget _buildEmptyState() {
    return Container(
      height: 200,
      child: const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.inbox_outlined,
              color: Colors.white54,
              size: 48,
            ),
            SizedBox(height: 16),
            Text(
              'No comics',
              style: TextStyle(
                color: Colors.white54,
                fontSize: 16,
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<dynamic> _getComicsWithoutFirst(List<dynamic>? comics) {
    if (comics == null || comics.isEmpty) {
      return [];
    }
    return comics.skip(1).toList();
  }

  Widget _hengxiangListWidgt(
      BuildContext context, ComicCategoryData category, bool isDelFirst) {
    List<ComicItemModel>? comicsToShow = [];
    if (isDelFirst) {
      comicsToShow =
          _getComicsWithoutFirst(category.comics).cast<ComicItemModel>();
    } else {
      comicsToShow = category.comics;
    }

    if (comicsToShow == null || comicsToShow.isEmpty) {
      return const SizedBox(
        height: 120,
        child: Center(
          child: Text(
            'No comics available',
            style: TextStyle(
              color: Colors.white54,
              fontSize: 14,
            ),
          ),
        ),
      );
    }

    return SizedBox(
      height: 120,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: isDelFirst ? 0 : 16),
        itemCount: comicsToShow.length,
        itemBuilder: (context, index) {
          final comic = comicsToShow?[index];
          return GestureDetector(
            onTap: () {
              // 直接跳转到漫画阅读页面
              if (comic?.id != null) {
                context.pushNamed(
                  'direct_reader',
                  pathParameters: {
                    'chapterId': comic?.id ?? "",
                    'comicId': comic?.id ?? "",
                  },
                );
              }
            },
            child: Container(
              width: 80,
              margin: const EdgeInsets.only(right: 12),
              child: Column(
                children: [
                  Expanded(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      // 让 ClipRRect 尽可能填充宽度
                      child: SizedBox(
                        width: double.infinity,
                        child: CachedNetworkImage(
                          imageUrl: comic?.cover ?? '',
                          // 让图片填充宽度，高度自适应
                          fit: BoxFit.cover,
                          placeholder: (context, url) => Container(
                            color: Colors.grey[800],
                            width: double.infinity,
                            child: const Icon(
                              Icons.image,
                              color: Colors.white54,
                            ),
                          ),
                          errorWidget: (context, url, error) => Container(
                            color: Colors.grey[800],
                            child: const SizedBox(
                              width: double.infinity,
                              child: Center(
                                child: Icon(
                                  Icons.broken_image,
                                  color: Colors.white54,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    comic?.title ?? 'Unknown',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

// 完整实现 TwoByThreeGridDemo 组件
// ignore: must_be_immutable
class TwoByThreeGridDemo extends StatelessWidget {
  List<ComicItemModel>? similarComic;

  TwoByThreeGridDemo({super.key, this.similarComic});

  @override
  Widget build(BuildContext context) {
    // 如果没有数据，返回空容器
    if (similarComic == null || similarComic!.isEmpty) {
      return Container();
    }
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: GridView.builder(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          childAspectRatio: 0.7,
          crossAxisSpacing: 12,
          mainAxisSpacing: 12,
        ),
        itemCount: similarComic!.length, // 2行3列 = 6个项目
        itemBuilder: (context, index) {
          final comic = similarComic![index];
          return GestureDetector(
            onTap: () {
              // context.push('/comic/demo_$index');
              if (comic.id != null) {
                context.pushNamed(
                  'direct_reader',
                  pathParameters: {
                    'chapterId': comic.id ?? "",
                    'comicId': comic.id ?? "",
                  },
                );
              }
            },
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Expanded(
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: CachedNetworkImage(
                      imageUrl: comic.cover ?? '',
                      fit: BoxFit.cover,
                      width: double.infinity,
                      placeholder: (context, url) => Container(
                        color: const Color(0xFF2A1F3D),
                        child: const Center(
                          child: CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation<Color>(
                                Color(0xFF8A7CA8)),
                            strokeWidth: 2.0,
                          ),
                        ),
                      ),
                      errorWidget: (context, url, error) => Container(
                        color: const Color(0xFF2A1F3D),
                        child: const Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.broken_image,
                                color: Color(0xFF8A7CA8), size: 24),
                            SizedBox(height: 4),
                            Text(
                              '加载失败',
                              style: TextStyle(
                                color: Color(0xFF8A7CA8),
                                fontSize: 10,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  comic.title ?? 'Unknown',
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
